package com.easy.controller;

import com.easy.bean.User;
import com.easy.common.CommonResult;
import com.easy.service.ILoginService;
import com.easy.util.CaptchaUtil;
import com.easy.util.JWTUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
public class LoginController {

    @Autowired
    ILoginService loginS;

    @Autowired
    HttpSession session;


    @GetMapping("/currentusername")
    public CommonResult currentUserName(HttpServletRequest request) {
        String token = request.getHeader("Authorization");

        if (token == null || token.isEmpty()) {
            return CommonResult.fail("Authorization token is missing");
        }

        Map map = loginS.decode(token);
        return CommonResult.success(map);
    }

    // 登录
    @PostMapping("login")
    public CommonResult doLogin(@RequestBody User user, @RequestParam String captcha) {
        System.out.println("验证码: " + captcha);

        boolean isCaptchaValid = CaptchaUtil.verifyCaptcha(session, captcha);
        if (!isCaptchaValid) {
            return CommonResult.fail(401, "验证码错误");
        }
        String token = loginS.Login(user);
        if (token == null) {
            return CommonResult.fail(403, "登录失败");
        } else {
            session.setAttribute("token", token);  // 保存token到会话中
            return CommonResult.success(200, "登陆成功", token);
        }
    }

    // 退出登录
    @PostMapping("logout")
    public CommonResult doLogout() {
        session.invalidate();  // 使当前会话失效
        return CommonResult.success(200, "登出成功");
    }
}
